<template>
  <!-- 弹出层 -->
  <el-dialog v-model="visible" :title="isCreate ? '添加用户' : '编辑用户'" width="50%" :before-close="closeUserAdd">
    <!-- 内容部分 -->
    <div class="userDialog_Form">
      <el-form size="small" :model="userForm" ref="userFormRef" label-width="120px" :rules="userFormRules">
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="userForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="isCreate">
          <el-input v-model="userForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phoneNumber">
          <el-input v-model="userForm.phoneNumber" type="number"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <!-- 底部按钮部分 这是一个具名插槽-->
    <template #footer>
      <div>
        <el-button type="success" size="small" @click="submitUserAdd">提交</el-button>
        <el-button type="default" size="small" @click="closeUserAdd">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, toRefs, watch } from "vue";
import { addUser, putUserInfo } from "network/user.js";
let props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  isCreate: {
    type: Boolean,
    default: false, //false  是修改  true是创建
  },
  userForm: {
    type: Object,
    default() {
      //修改的时候穿进来的对象  复杂类型要用这种方式定义
      return {};
    },
  },
});
let emits = defineEmits(["closeUserAdd", "refreshUserList"]);
const { proxy } = getCurrentInstance();

let userFormRef = ref(null);

const userFormRules = reactive({
  userName: [
    {
      required: true,
      message: "请输入用户名称",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入用户密码",
      trigger: "blur",
    },
  ],
});

//关闭对话框
const closeUserAdd = () => {
  userFormRef.value.resetFields();
  emits("closeUserAdd");
};
//添加/更新用户
const submitUserAdd = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      let res = ref([]);
      if (props.isCreate) res = await addUser(props.userForm);
      else res = await putUserInfo(props.userForm);
      if (!res.success) return proxy.$notify.error({ message: res.msg, showClose: true });
      proxy.$notify.success({ message: res.msg, showClose: true });
      emits("refreshUserList");
      closeUserAdd();
    }
  });
};
</script>

<style lang="less" scoped></style>
